<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElButton, ElMessage, ElDialog, ElInputNumber, ElMessageBox, ElInput, ElForm, ElFormItem } from 'element-plus'
import { useCartStore } from '../stores/cartStore'
import { getProductById } from '../api/home'
import { createOrder } from '../api/order'
import { getUserId } from '../stores/userStore'
import { format } from 'date-fns'

const route = useRoute()
const router = useRouter()
const productId = route.params.id
const productInfo = ref(null)
const cartStore = useCartStore()
const dialogVisible = ref(false)
const quantity = ref(1)
const shippingAddress = ref('') // 新增地址输入

const fetchProductInfo = async () => {
  if (!productId) {
    console.error('Product ID is undefined');
    ElMessage.error('商品ID未定义');
    router.push('/');
    return;
  }

  try {
    const response = await getProductById(productId);
    if (response.data.code === 1) {
      productInfo.value = {
        id: response.data.data.productid,
        text: response.data.data.title,
        price: Number(response.data.data.price),
        description: response.data.data.description,
        src: response.data.data.productimg,
        alt: response.data.data.title
      };
    } else {
      ElMessage.error('商品不存在');
      router.push('/');
    }
  } catch (error) {
    console.error('Error loading product:', error);
    ElMessage.error('加载商品信息失败');
  }
}

const addToCart = () => {
  if (productInfo.value) {
    cartStore.addToCart(productInfo.value)
    ElMessage({
      message: '已加入购物车',
      type: 'success',
    })
  }
}

const buyNow = () => {
  dialogVisible.value = true
}

const handleBuyNowConfirm = async () => {
  // 验证输入
  if (quantity.value < 1) {
    ElMessage.error('请选择有效的购买数量');
    return;
  }

  if (!shippingAddress.value.trim()) {
    ElMessage.error('请填写收货地址');
    return;
  }

  const userId = getUserId();
  if (!userId) {
    ElMessageBox.alert('请先登录', '提示', {
      confirmButtonText: '确定',
    })
    return;
  }

  const orderData = {
    order: {
      userid: userId,
      totalprice: productInfo.value.price * quantity.value,
      status: '未支付',
      shipping_address: shippingAddress.value, // 使用用户输入的地址
      createtime: format(new Date(), 'yyyy-MM-dd HH:mm:ss')
    },
    orderProducts: [{
      productid: productInfo.value.id,
      orderprice: productInfo.value.price,
      quantity: quantity.value
    }]
  };

  try {
    const response = await createOrder(orderData);
    if (response.data.code === 1) {
      ElMessageBox.alert(`订单创建成功`, {
        confirmButtonText: '确定',
      }).then(() => {
        // 清空输入
        quantity.value = 1
        shippingAddress.value = ''
        dialogVisible.value = false
      })
    } else {
      ElMessageBox.alert(`订单创建失败: ${response.data.msg}`, '结算失败', {
        confirmButtonText: '确定',
      })
    }
  } catch (error) {
    console.error('Error creating order:', error);
    ElMessageBox.alert('订单创建失败，请稍后再试', '结算失败', {
      confirmButtonText: '确定',
    })
  }
}

onMounted(() => {
  fetchProductInfo()
})
</script>

<template>
  <div class="product-container">
    <div class="product-detail" v-if="productInfo">
      <!-- 商品图片 -->
      <div class="product-image">
        <img :src="productInfo.src" :alt="productInfo.alt">
      </div>

      <!-- 商品信息 -->
      <div class="product-info">
        <h2 class="product-title">{{ productInfo.text }}</h2>
        <div class="price">¥{{ productInfo.price }}</div>
        <div class="product-desc">
          <p>商品描述：</p>
          <p>{{ productInfo.description }}</p>
        </div>
      </div>
    </div>

    <!-- 商品操作按钮 -->
    <div class="action-buttons">
      <el-button type="warning" size="large" @click="addToCart" class="action-button">
        加入购物车
      </el-button>
      <el-button type="danger" size="large" @click="buyNow" class="action-button">
        直接购买
      </el-button>
    </div>

    <!-- 购买对话框 -->
    <el-dialog v-model="dialogVisible" title="填写订单信息" width="90%" class="order-dialog">
      <el-form label-width="100px">
        <el-form-item label="购买数量">
          <el-input-number v-model="quantity" :min="1" :max="99" controls-position="right" class="full-width" />
        </el-form-item>

        <el-form-item label="收货地址">
          <el-input v-model="shippingAddress" placeholder="请输入详细收货地址" clearable type="textarea" :rows="3" resize="none"
            class="full-width" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBuyNowConfirm">立即购买</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.product-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  padding-bottom: 120px;
}

.product-image {
  width: 100%;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px;
}

.product-image img {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

.product-info {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin: 15px;
}

.product-title {
  font-size: 20px;
  color: #333;
  margin: 0 0 10px 0;
}

.price {
  color: #ff6b6b;
  font-size: 24px;
  font-weight: bold;
  margin: 15px 0;
}

.product-desc {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.product-desc p {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin: 5px 0;
}

.action-buttons {
  position: fixed;
  bottom: 55px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  padding: 10px 20px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 999;
}

.action-button {
  flex: 1;
  margin: 0 5px !important;
  height: 40px !important;
}

/* 对话框样式 */
.order-dialog {
  .el-dialog__body {
    padding: 20px;
  }

  .full-width {
    width: 100%;
  }

  .dialog-footer {
    padding-top: 15px;
    border-top: 1px solid #eee;
  }
}

@media (min-width: 768px) {
  .order-dialog {
    width: 50%;
  }

  .product-detail {
    display: flex;
    padding: 30px;
    gap: 30px;

    .product-image {
      flex: 0 0 400px;
      margin-bottom: 0;
    }

    .product-info {
      flex: 1;
      margin: 0;
    }
  }
}
</style>